import json

from django.http import JsonResponse
from .models import User
import hashlib


def register(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码

    account = data.get('account')
    password = hash_password(data.get('password'))
    role = "user"
    nickname = "Me"
    ent_user_id = data.get('ent_user_id')

    if User.objects.filter(account=account).exists():
        return JsonResponse({'message': '账户已存在'}, status=202)

    user = User.objects.create_user(account=account, password=password, nickname=nickname, role=role,
                                    ent_user_id=ent_user_id)
    return JsonResponse({'message': 'success', 'user_info': user.serialize()}, status=200)


def login(request):
    data = json.loads(request.body.decode('utf-8'))  # 确保使用正确的编码

    account = data.get('account')
    password = data.get('password')

    try:
        user = User.objects.get(account=account)
        if check_password(password, user.password):
            return JsonResponse({'message': 'success', 'user_info': user.serialize()}, status=200)
        else:
            return JsonResponse({'message': '密码错误'}, status=202)
    except User.DoesNotExist:
        # return JsonResponse({'message': '密码错误'}, status=202)
        return register(request)


# return JsonResponse({'message': '登录错误'}, status=202)


def hash_password(password):
    hashed_password = hashlib.md5((password).encode()).hexdigest()
    return hashed_password


def check_password(password, hashed_password):
    return hashed_password == hash_password(password)
# user / jcy7829
